﻿import axios from 'axios'
import { MessageBox } from 'element-ui'
import { showLoading, tryHideLoading } from './loading.js'
// import store from '../store'
import { getToken, removeToken } from '@/utils/auth'
// import Router from '@/router'
// 封装axios请求
// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api 的 base_url
  // baseURL: window.configs.API_USER, // api 的 base_url
  timeout: 40000 // 请求超时时间
})
var configUrl = null
// request拦截器
service.interceptors.request.use(
  config => {
    if (config.url === '/querySummary/importOperatorUser.do') {
      config.timeout = 3000
      configUrl = true
    }
    if (getToken()) {
      config.headers['x-token'] = getToken() // 让每个请求携带自定义token 根据实际情况自行修改
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// 全局加载loading方法 (请求拦截器)
service.interceptors.request.use(
  config => {
    // tryHideLoading() // 避免切换请求遮罩不消失，所以就先消失遮罩
    if (config.url !== '/tools/functionTypeList.do' && config.url !== '/tools/membershipLevelList.do') {
      showLoading()
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// response 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.resultCode !== '0000' && response.data.type !== 'application/vnd.ms-excel') {
      tryHideLoading()
      if (res.resultCode === '9995') {
        MessageBox.alert(res.resultDesc, '提示', {
          confirmButtonText: '确定',
          callback: action => {
            removeToken()
            // window.location.replace(process.env.VUE_APP_BASE_LOGIN)
            window.location.replace(window.location.replace(window.bossUrl.API_LOGIN))
          }
        })
      } else {
        MessageBox.alert(res.resultDesc, '提示', {
          confirmButtonText: '确定',
          callback: action => {
          }
        })
        return response.data
      }
    } else {
      tryHideLoading()
      return response.data
    }
  },
  error => {
    console.log('err' + error) // for debug
    tryHideLoading()
    if (configUrl) {
      MessageBox.alert('后台正在导入数据，请稍等', '提示', {
        confirmButtonText: '确定',
        callback: action => {
        }
      })
      return
    }
    MessageBox.alert('网络错误，请重试', '提示', {
      confirmButtonText: '确定',
      callback: action => {
        // ocation.reload()
        // window.history.go(-1)
        removeToken()
        /* Router.replace({
          path: '/login'
        }) */
        // window.location.replace(process.env.VUE_APP_BASE_LOGIN)
        window.location.replace(window.bossUrl.API_LOGIN)
      }
    })
    return Promise.reject(error)
  }
)
export default service
